package io.renren.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.renren.dao.ActAssigndtlDao;
import io.renren.entity.ActAssigndtlEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.renren.dao.ActAssignDao;
import io.renren.entity.ActAssignEntity;
import io.renren.service.ActAssignService;



@Service("actAssignService")
public class ActAssignServiceImpl implements ActAssignService {
	@Autowired
	private ActAssignDao actAssignDao;
	@Autowired
	private ActAssigndtlDao actAssigndtlDao;
	
	@Override
	public ActAssignEntity queryObject(Integer id){
		return actAssignDao.queryObject(id);
	}
	
	@Override
	public List<ActAssignEntity> queryList(Map<String, Object> map){
		return actAssignDao.queryList(map);
	}
	
	@Override
	public int queryTotal(Map<String, Object> map){
		return actAssignDao.queryTotal(map);
	}
	
	@Override
	public void save(JSONObject params){
		ActAssignEntity actAssign =  params.getObject("actAssign",ActAssignEntity.class);
		List<ActAssigndtlEntity> actAssigndtlList = JSON.parseArray(params.get("actAssigndtlList").toString(), ActAssigndtlEntity.class);

		actAssignDao.save(actAssign);
		saveDtl(actAssigndtlList,actAssign);
	}

	@Override
	public void update(JSONObject params){

		ActAssignEntity actAssign = JSON.parseObject(params.get("actAssign").toString(), ActAssignEntity.class);
		List<ActAssigndtlEntity> actAssigndtlList = JSON.parseArray(params.get("actAssigndtlList").toString(), ActAssigndtlEntity.class);
		actAssignDao.update(actAssign);
		//明细有多条，可能既有更新删除增加操作，所以先删在增
		actAssigndtlDao.deleteByHeadId(actAssign.getId());
		saveDtl(actAssigndtlList,actAssign);
	}
	
	@Override
	public void delete(Integer id){
		actAssignDao.delete(id);
	}
	
	@Override
	public void deleteBatch(Integer[] ids){
		actAssignDao.deleteBatch(ids);
		for( int id:ids){
			actAssigndtlDao.deleteByHeadId(id);//删除关联的考评信息
		}
	}

	@Override
	public Map info(Integer id){
		ActAssignEntity actAssign = actAssignDao.queryObject(id);
		List<ActAssigndtlEntity> actAssigndtlList =actAssigndtlDao.queryListByHead(id);
		Map map=new HashMap();
		map.put("actAssign", actAssign);
		map.put("actAssigndtlList", actAssigndtlList);
		return map;
	}



	void saveDtl(List<ActAssigndtlEntity>  list,ActAssignEntity actAssign){
		int num=1;//代表审批级别
		for (ActAssigndtlEntity pojo : list) {
			pojo.setHeadId(actAssign.getId());
			pojo.setCusername(actAssign.getCusername());
			pojo.setCdate(actAssign.getCdate());
			pojo.setLevel(num);
			actAssigndtlDao.save(pojo);
			num++;
		}
	}
	
}
